package com.apisix.service.controller;

import com.apisix.service.entity.Service;
import com.apisix.service.service.ServiceEntityService;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/services")
public class ServiceController {

    private final ServiceEntityService serviceEntityService;

    @Autowired
    public ServiceController(ServiceEntityService serviceEntityService) {
        this.serviceEntityService = serviceEntityService;
    }

    @GetMapping
    public ResponseEntity<List<Service>> getAllServices() {
        List<Service> services = serviceEntityService.getAllServices();
        return ResponseEntity.ok(services);
    }

    @GetMapping("/{id}")
    public ResponseEntity<Service> getServiceById(@PathVariable Long id) {
        return serviceEntityService.getServiceById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @GetMapping("/service/{serviceId}")
    public ResponseEntity<Service> getServiceByServiceId(@PathVariable String serviceId) {
        return serviceEntityService.getServiceByServiceId(serviceId)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping
    public ResponseEntity<?> createService(@RequestBody Service service) {
        try {
            // 检查serviceId是否已存在
            if (service.getServiceId() != null && !service.getServiceId().isEmpty() && serviceEntityService.existsByServiceId(service.getServiceId())) {
                return ResponseEntity.badRequest().body(Map.of("error", "ServiceId已存在"));
            }
            
            Service createdService = serviceEntityService.createService(service);
            return ResponseEntity.status(HttpStatus.CREATED).body(createdService);
        } catch (JsonProcessingException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", "创建服务失败: " + e.getMessage()));
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<?> updateService(@PathVariable Long id, @RequestBody Service serviceDetails) {
        try {
            return serviceEntityService.updateService(id, serviceDetails)
                    .map(ResponseEntity::ok)
                    .orElse(ResponseEntity.notFound().build());
        } catch (JsonProcessingException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", "更新服务失败: " + e.getMessage()));
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteService(@PathVariable Long id) {
        boolean deleted = serviceEntityService.deleteService(id);
        if (deleted) {
            return ResponseEntity.noContent().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    
    @PostMapping("/sync")
    public ResponseEntity<?> syncServicesFromApisix() {
        try {
            serviceEntityService.syncServicesFromApisix();
            return ResponseEntity.ok(Map.of("message", "服务同步成功"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", "同步服务失败: " + e.getMessage()));
        }
    }
} 